<template>
	<view class="page">
		<!-- <u-navbar :is-back="true" title="订单确认" back-icon-color='#FFFFFF' title-color="#ffffff" :background="{backgroundColor: 'none'}"></u-navbar> -->
		<view class="top-background">
			<!-- <image class="background-icon" mode="widthFix" src="../../static/order/address_background.png"></image> -->
			<view style="height: 30px;"></view>
			<view class="address-content">
				<view class="delivery-list">
					<view class="delivery-item" :class="{'active':deliveryMethod==item.code}" v-for="(item,index) in deliveryMethodList" :key="index" @click="chooseDelivery(item.code)">{{item.name}}</view>
					<view v-if="deliveryMethodList.length==0" style="min-height: 80px;">无配送方式</view>
				</view>
				<!--快递-->
				<view v-if="deliveryMethod=='express_delivery'">
					<view class="address" @click="toAddressList">
						<view class="left" v-if="address">
							<view class="title">
								<text>{{address.consignee}}</text>
								<text>{{address.phone}}</text>
							</view>
							<view class="address-detail">
								{{address.province+address.city+address.area+address.address}}
							</view>
						</view>
						<view class="left" style="height: 50px;line-height: 50px;" v-else>请选择收货地址</view>
						<image style="width: 6px" src="../../static/cart/fanhui.png"></image>
					</view>
					<view class="time">
						<text style="font-size: 14px;color: #2A2A2A;">运费</text>
						<text style="font-size: 12px;color: #636363;">{{address&&address.id?'￥'+goodsDetail.delivery_fee:'请选择地址'}}</text>
					</view>
				</view>
				<!--自提-->
				<view v-if="deliveryMethod=='self_pick'">
					<view class="address" @click="toWxMap">
						<view class="left">
							<view class="title">
								<text style="margin-left: 0;">{{merchant.name}}</text>
							</view>
							<view class="address-detail">
								{{merchant.address}}
							</view>
						</view>
						<image style="width: 6px" src="../../static/cart/fanhui.png"></image>
					</view>
					<view class="self-pick">
						<text style="font-size: 14px;color: #2A2A2A;">手机号码</text>
						<input type="number" v-model="phone" placeholder="手机号码" />
					</view>
				</view>
				<!--即时配送-->
				<view v-if="deliveryMethod=='instant_delivery'">
					<view class="address" @click="toAddressList">
						<view class="left" v-if="address">
							<view class="title">
								<text>{{address.consignee}}</text>
								<text>{{address.phone}}</text>
							</view>
							<view class="address-detail">
								{{address.province+address.city+address.area+address.address}}
							</view>
						</view>
						<view class="left" style="height: 50px;line-height: 50px;" v-else>请选择收货地址</view>
						<image style="width: 6px" src="../../static/cart/fanhui.png"></image>
					</view>
					<view class="time">
						<text style="font-size: 14px;color: #2A2A2A;">运费</text>
						<text style="font-size: 12px;color: #636363;">￥{{goodsDetail.delivery_fee}}</text>
					</view>
					<view class="notice" v-if="goodsDetail.notice">{{goodsDetail.notice}}</view>
				</view>

			</view>

			<view class="prescription-section" v-if="prescription_order==1" @click="toPrescription">
				<view class="content">
					<view class="left-content" v-if="prescriptionInfo">
						<text>处方单信息</text>
						<view>
							<text>{{prescriptionInfo.patient_name}}</text>
							<text>{{prescriptionInfo.patient_phone}}</text>
						</view>
					</view>
					<view class="left-content spec-text" v-else>请填写处方单信息</view>
					<view class="perfect-btn">
						去完善
					</view>
				</view>
			</view>

			<view class="content-section">
				<!--商品列表-->
				<view class="goods">
					<view class="shop-header">
						<image class="shop-icon" src="../../static/cart/jiaonang.png"></image>
						<text>{{merchant.name}}</text>
						<!-- <image class="back" src="../../static/cart/fanhui.png"></image> -->
					</view>
					<view class="goods-list">
						<view class="goods-item" v-for="(item,index) in goodsDetail.goods_info" :key="index">
							<image :src="item.thumb_url"></image>
							<view class="item-right">
								<view class="detail-info">
									<view class="name">{{item.name}}</view>
									<view class="count">￥{{item.selling_price}}x{{item.num}}</view>
								</view>
								<view class="price">￥{{item.selling_price*item.num}}</view>
							</view>
						</view>
					</view>
				</view>

				<!-- <view class="receiver-list">
					<view class="title">收货方式</view>
					<view class="receiver-item" v-for="(item,index) in deliveryMethodList" :key="index"  @click="chooseDelivery(item.code)">
						<view class="item-left">
							<text>{{item.name}}</text>
						</view>
						<view class="select">
							<image v-if="deliveryMethod==item.code" src="../../static/order/gou_xuanzhong.png"></image>
							<image v-else src="../../static/order/tuoyuan.png"></image>
						</view>
					</view>
				</view> -->

				<view class="order_information">
					<view class="order_information_item" @click="toCoupon">
					  <view>优惠券</view>
					  <!-- <view style="color: grey;">{{coupon.name||'未使用 >'}}</view> -->
					  <view style="display: flex;align-items: center">
						  <view>{{coupon.id?'-￥'+goodsDetail.coupon_money:'未使用'}}</view>
						  <image v-if="!coupon.name" style="width: 6px;height: 11px;margin-left: 5px;margin-top: 2px;" src="../../static/cart/fanhui.png"></image>
					  </view>
					</view>
					<view class="order_information_item">
						<view>立减</view>
						<view>-￥{{goodsDetail.reduce_amount}}</view>
					</view>
				</view>

				<view class="remark">
					<text class="text">备注</text>
					<input v-model="remark" placeholder="选填,可以告诉我们您的需求" />
				</view>
			</view>

			<view style="width: 100vw;height: 80px;"></view>

		</view>

		<!-- 结算栏 -->
		<view class="foot-section">
			<view class="foot">
				<view class="footer_left"></view>
				<view class="footer_right">
					<view class="footer_right_price"><span style="color: #FFFFFF;font-size: 12px;">应付款：</span>￥{{goodsDetail.pay_amount}}
					</view>
					<button :disabled="submitBtnDisable" class="footer_right_pay" @click="orderConfirm">
						<span>{{prescription_order==1?'提交需求':'确认下单'}}</span>
					</button>
				</view>
			</view>
		</view>
		<!-- 结算栏结束 -->

	</view>
</template>

<script>
	export default {
		computed: {
			goodsDetail() {
				return this.$store.state.modulesOrder.order
			},
			coupon: {
				get: function () {
					return this.$store.state.modulesCoupon.coupon
				}
			},
		},
		data() {
			return {
				payType: 0,
				/* payArray:['微信支付', '货到付款'], */
				companyId: [],
				companyArr: [],
				companyIndex: 0,
				orderId: "",   //订单号
				remark: "",    //备注信息
				address: "",  //地址详情
				company: '',//快递公司
				type: '',//订单类型shop_cart来自购物车
				shopType: '',//integral积分,bargain砍价,common普通商品
				deliveryMethodList: [],
				deliveryMethod: '',
				merchant: '',
				phone: '',//自提的联系方式
				outOfRange: false,
				isConfirmOrder: false,
				agent_phone_number: '',//药师电话
				agent_email: '',//药师邮箱
				prescription_order: '',//判断是否有处方药1表示有处方药
				prescriptionInfo: '',
				submitBtnDisable: false
			}
		},
		onLoad(options) {
			//获取商店信息
			this.merchant = wx.getStorageSync("merchant")
			this.agent_phone_number = options.agent_phone_number
			this.agent_email = options.agent_email
			this.prescription_order = options.prescription_order
			let title = ''
			if(this.prescription_order == 1){
				title = '需求确认'
			} else {
				title = '订单确认'
			}
			wx.setNavigationBarTitle({
				title: title
			})
		},
		methods: {

			//解除禁用提交按钮
			enableSubmitBtn() {
				this.submitBtnDisable = false
			},

			//禁用提交按钮
			disableSubmitBtn() {
				this.submitBtnDisable = true
			},

			toPrescription() {
				this.$currency.navigateTo('/pages/prescription/prescriptionInfo?from=order')
			},

			async getAddressDetails() {
				let userToken = wx.getStorageSync('userToken')
				if (this.$store.state.modulesAddress.address) {
					this.address = this.$store.state.modulesAddress.address;
					return
				}
				let res = await this.$api.getShippingAddress({user_token: userToken}, this.$baseUrl)
				let address = res.data.data.filter((item) => {
					return item.is_default == '1'
				})
				if (address.length != 0) {
					this.address = address[0]
				} else {
					this.address = ''
				}
			},

			//获取商家支持的收货方式
			async getMerchantSupportDeliveryMethod() {
				let res = await this.$api.getMerchantSupportDeliveryMethod({merchant_id: this.merchant.merchant_id}, this.$baseUrl)
				if (res.data.level == "success") {
					this.deliveryMethodList = res.data.data;
					if (!this.deliveryMethod) {
						this.deliveryMethod = this.deliveryMethodList[0].code
					}
				} else {
					wx.showToast({
						title: res.data.message,
						icon: 'none'
					})
				}
			},

			//选择收货方式
			chooseDelivery(menthod) {
				this.deliveryMethod = menthod
				this.submitOrder()
			},

			//预览订单
			async submitOrder() {
				wx.showLoading({
					title: '加载中'
				})
				console.log('submitOrder',this.goodsDetail)
				let userToken = wx.getStorageSync('userToken')
				let res = await this.$api.submitOrder({
					shop_cart_ids: this.goodsDetail.shop_cart ? this.goodsDetail.shop_cart : '',
					medicine_id: this.goodsDetail.medicine_id ? this.goodsDetail.medicine_id : '',
					address_id: this.address.id,
					delivery_method: this.deliveryMethod,
					num: this.goodsDetail.num ? this.goodsDetail.num : '',
					user_token: userToken,
					coupon_id: this.coupon ? this.coupon.coupon_id || '' : '',
				}, this.$baseUrl)
				if (res.data.level == "success") {
					wx.hideLoading()
					res.data.data.shop_cart = this.goodsDetail.shop_cart ? this.goodsDetail.shop_cart : ''
					res.data.data.medicine_id = this.goodsDetail.medicine_id ? this.goodsDetail.medicine_id : ''
					res.data.data.num = this.goodsDetail.num ? this.goodsDetail.num : ''
					this.$store.dispatch('setOrder', res.data.data)
					if (this.deliveryMethod == 'instant_delivery' && this.address) {
						if (res.data.data.notice) {
							this.outOfRange = true
							wx.showToast({
								title: "超出配送范围",
								icon: 'none'
							})
						} else {
							this.outOfRange = false
						}
					}
				} else {
					wx.hideLoading()
					wx.showToast({
						title: res.data.message,
						icon: 'none'
					})
				}
			},

			//生成订单
			async orderConfirm() {
				let userToken = wx.getStorageSync('userToken');

				let addressId = this.address.id
				if (this.deliveryMethod == "self_pick") {
					if (!this.checkPhone(this.phone)) {
						wx.showToast({
							title: '手机格式错误',
							icon: 'none'
						})
						return
					}
					addressId = ""
				} else {
					if (this.address == '') {
						wx.showToast({
							title: '未填收货地址',
							icon: 'none'
						})
						let value = this.goodsDetail
						setTimeout(() => {
							wx.navigateTo({
								url: '../address/address'
							})
						}, 1000)
						return
					}
				}

				if (this.deliveryMethod == "instant_delivery") {
					if (this.outOfRange) {
						wx.showToast({
							title: '超出配送范围',
							icon: 'none'
						})
						return
					}
				}

				this.disableSubmitBtn()
				wx.showLoading({
					title: '正在创建订单'
				})
				let params = {
					num: this.goodsDetail.num ? this.goodsDetail.num : '',
					shop_cart_ids: this.goodsDetail.shop_cart ? this.goodsDetail.shop_cart : '',
					medicine_id: this.goodsDetail.medicine_id ? this.goodsDetail.medicine_id : '',
					user_token: userToken,
					address_id: addressId,
					remark: this.remark,
					delivery_method: this.deliveryMethod,
					phone: this.phone,
					coupon_id: this.coupon ? this.coupon.coupon_id || '' : '',
					agent_email: this.agent_email,
					agent_phone_number: this.agent_phone_number
				}
				//设置处方药信息
				let prescriptionInfo = this.$store.state.prescriptionInfo
				if (this.prescription_order == 1) {//先判断是否处方订单
					if (!prescriptionInfo.user_drug_id) {
						this.$currency.showToast('请填写处方信息')
						return
					}
					//设置都要带的参数
					params.prescription_order = 1 //是否处方订单
					params.user_drug_id = prescriptionInfo.user_drug_id //用药人ID
					params.has_prescription = prescriptionInfo.has_prescription //是否有处方单
					params.prescription_imgs = prescriptionInfo.prescription_imgs //处方单图片
					//设置没有处方单要传的参数
					if(prescriptionInfo.has_prescription == 0){
						params.disease_info = prescriptionInfo.disease_info //疾病名称
						params.diagnose_description = prescriptionInfo.diagnose_description //疾病描述
						params.diagnostic_level = prescriptionInfo.diagnostic_level //诊断级别
						params.drug_usage = prescriptionInfo.drug_usage //既往用药情况
					}
				}

				let res = await this.$api.buildOrder(params, this.$baseUrl)
				this.isConfirmOrder = true
				if (res.data.level == 'success') {
					wx.hideLoading()
					await this.payment(res.data.data.order_num)
				} else if (res.data.level == 'paying') {
					wx.showToast({title: res.data.message, icon: "none"})
					setTimeout(() => {
						wx.redirectTo({
							url: '../orderDetail/orderDetail?num=' + res.data.data.order_num
						})
					}, 1500)
				} else {
					wx.hideLoading()
					wx.showToast({
						title: res.data.message,
						icon: 'none'
					})
					this.enableSubmitBtn()
				}
			},

			//支付
			async payment(order_num) {
				let userToken = wx.getStorageSync('userToken')
				let res = await this.$api.weChatPayment({
					order_num: order_num,
					user_token: userToken
				}, this.$baseUrl)
				if (res.data.level == "success") {
					let data = res.data.data
					wx.requestPayment({
						timeStamp: data.timeStamp,
						nonceStr: data.nonceStr,
						package: data.package,
						signType: data.signType,
						paySign: data.paySign,
						success() {
							wx.showToast({
								title: '支付成功',
								icon: 'success',
								duration: 1500
							})
							setTimeout(() => {
								wx.redirectTo({
									url: '../orderDetail/orderDetail?num=' + order_num
								})
							}, 1500)
						},
						fail(res) {
							wx.showToast({
								title: '取消支付',
								icon: 'none',
								duration: 1500
							})
							setTimeout(() => {
								wx.redirectTo({
									url: '../orderDetail/orderDetail?num=' + order_num
								})
							}, 1500)
						}
					})
				} else {
					this.enableSubmitBtn()
					wx.showToast({
						title: res.data.message,
						icon: 'none'
					})
				}

			},

			// 手机号码验证 11位数字
			checkPhone(phoneNumb) {
				let user = /^1[0-9]{10}$/
				if (!user.test(phoneNumb)) {
					return false
				}
				return true
			},

			//跳转微信地图
			toWxMap() {
				let _this = this;
				wx.openLocation({
					latitude: parseFloat(_this.merchant.lat),
					longitude: parseFloat(_this.merchant.lng),
					success: (res) => {
						console.log(res)
					},
					fail: (err) => {
						console.log(err)
					}
				})
			},

			//跳转选择地址
			toAddressList() {
				this.isConfirmOrder = false
				wx.navigateTo({
					url: '../address/address'
				})
			},

			toCoupon() {
				this.isConfirmOrder = false

				let userToken = wx.getStorageSync('userToken')

				let req = {
					shop_cart_ids: this.goodsDetail.shop_cart ? this.goodsDetail.shop_cart : '',
					medicine_id: this.goodsDetail.medicine_id ? this.goodsDetail.medicine_id : '',
					address_id: this.address.id,
					delivery_method: this.deliveryMethod,
					num: this.goodsDetail.num ? this.goodsDetail.num : '',
					user_token: userToken,
				}
				const params = JSON.stringify(req)
				wx.navigateTo({
					url: `/pages/coupon/coupon?type=order&params=${params}`
				})
			}

		},
		async onShow() {
			await this.getAddressDetails();
			//判断配送方式是否已经获取到了
			if(!(this.deliveryMethodList.length>0)){
				await this.getMerchantSupportDeliveryMethod()
			}
			//没有创建订单再去预览订单
			if (!this.isConfirmOrder) {
				await this.submitOrder()
			}
			if (this.prescription_order == 1) {
				this.prescriptionInfo = this.$store.state.prescriptionInfo
			}
		},
		onUnload() {
			this.$store.dispatch('setCoupon', {...{}, ...{}});
			this.$store.state.prescriptionInfo = ''
		},
	}
</script>

<style scoped lang="scss">
	@import "../../common/css/mixin";
	::-webkit-scrollbar {
	  width: 0;
	  height: 0;
	  color: transparent;
	}
	/* input::-webkit-input-placeholder {
	    font-size: 12px;
	} */
	.page{
		/* padding: 0 15px; */
		min-height: 100vh;
		background-color: #F0F0F0;
	}
	.top-background{
		/* height: 200px; */
		background-image: url('https://rzkeji.oss-cn-shenzhen.aliyuncs.com/web/yaojike2020/images/background/address_background.png');
		background-size: 100% auto;
		background-repeat: no-repeat;
		/* position: relative; */
		.background-icon{
			position: absolute;
			top: -40px;
			width: 100%;
		}
		.address-content{
			/* position: absolute;
			left: 50%;
			bottom: 0;
			transform: translateX(-50%); */
			margin: 0 auto;
			width: calc(100% - 60px);
			padding: 0 15px 15px;
			border-radius: 8px;
			background-color: #FFFFFF;
			.delivery-list{
				display: flex;
				padding: 10px 0;
				.delivery-item{
					padding: 3px 0;
					width: 80px;
					text-align: center;
					border-radius: 5px;
				}
				.active{
					background-color: #09C15F;
					color: #FFFFFF;
				}
			}
			.address{
				display: flex;
				align-items: center;
				/* padding-top: 15px; */
				border-bottom: 1px solid #EEEEEE;
				image{
					width: 6px;
					height: 11px;
				}
				.left{
					width: calc(100% - 16px);
					padding-right: 10px;
					display: flex;
					flex-direction: column;
					.title{
						color: #9EA0A0;
						font-size: 14px;
						padding-bottom: 10px;
						text:last-child{
						margin-left: 8px;
						}
					}
					.address-detail{
						padding-bottom: 10px;
						color: #2A2A2A;
						font-size: 15px;
						display: -webkit-box;
						-webkit-box-orient: vertical;
						-webkit-line-clamp: 2;
						overflow: hidden;
					}
				}
			}
			.time{
				display: flex;
				height: 30px;
				margin-top: 10px;
				align-items: center;
				justify-content: space-between;
			}
			.notice{
				color: red;
				font-size: 12px;
			}
			.self-pick{
				display: flex;
				margin-top: 10px;
				height: 30px;
				align-items: center;
				font-size: 14px;
				input{
					margin-left: 12px;
				}
			}
		}
	}

	.prescription-section{
		padding: 0 15px;
		margin-top: 10px;
		.content{
			display: flex;
			justify-content: space-between;
			align-items: center;
			width: 100%;
			background: #ffffff;
			color: grey;
			padding: 8px 10px;
			border-radius: 8px;
			box-sizing: border-box;
			.left-content{
				display: flex;
				flex-direction: column;
				font-size: 14px;
				height: 45px;
				justify-content: space-between;
				text:last-child{
					margin-left: 8px;
				}
			}
			.spec-text{
				justify-content: center !important;
				font-size: 30rpx;
				color: #333333;
			}
			.perfect-btn{
				padding: 8rpx 16rpx;
				border-radius: 25rpx;
				font-size: 20rpx;
				background-color: #09C15F;
				color: #ffffff;
			}
		}
	}

	.content-section{
		padding: 0 15px;
	}

	.goods{
		border-radius: 8px;
		overflow: hidden;
		margin-top: 15px;
		.shop-header{
			width:100%;
			height: 40px;
			background: #ffffff;
			display:flex;
			align-items:center;
			font-size: 14px;
			border-bottom: 1px solid #eeeeee;
			.shop-icon{
				width: 14px;
				height: 14px;
				margin-left: 10px;
			}
			.back{
				width: 5px;
				height: 10px;
			}
			text{
				color: #6C6D6C;
				margin: 0 10px;
			}
		}
		.goods-list{
			width:100%;
			background-color: #FFFFFF;
			display: flex;
			overflow: auto;
			position: relative;
			flex-direction: column;
			/* .into{
				width: 60px;
				height: 75px;
				padding-right: 5px;
				display: flex;
				align-items: center;
				position: absolute;
				right: 0;
				top: 0;
				background-color: #FFFFFF;
				image{
					width: 6px;
					height: 11px;
				}
				text{
					min-width: 50px;
					color: #8A8E8C;
					font-size: 12px;
				}
			} */
			.goods-item{
				padding: 15px;
				display: flex;
				image{
					width: 45px;
					height: 45px;
				}
				.item-right{
					width: calc(100vw - 115px);
					height: 100%;
					display: flex;
					justify-content: space-between;
					padding-left: 10px;
					.detail-info{
						display: flex;
						flex-direction: column;
						justify-content: space-between;
						font-size: 14px;
						width: 60%;
						.name{
							display: -webkit-box;
							-webkit-box-orient: vertical;
							-webkit-line-clamp: 3;
							 overflow: hidden;
						}
					}
					.price{
						margin-left: auto;
						margin-bottom: auto;
						/* min-width: 70px; */
					}
					.count{
						margin-top: 5px;
					}
				}
			}
		}
	}

	.receiver-list{
		width:100%;
		background-color: #FFFFFF;
		margin-top: 10px;
		border-radius: 8px;
		.title{
			color: #9EA09F;
			font-size: 13px;
			padding: 10px 0 10px 10px;
		}
		.receiver-item{
			display: flex;
			justify-content: space-between;
			color: #3E3E3E;
			font-size: 15px;
			padding: 8px 0;
			.item-left{
				margin-left: 10px;
			}
			image{
				width: 20px;
				height: 20px;
				margin-right: 10px;
			}
		}
	}

	/* 订单信息 */
	.order_information{
		width:100%;
		margin-top:10px;
		border-radius: 8px;
	}
	.order_information_item{
		width:100%;
		display: flex;
		align-items: center;
		justify-content: space-between;
		background: #fff;
		height: 40px;
		border-bottom: 1px solid #eee;
	}
	.order_information_item>view:nth-child(1),.order_information_remark>view:nth-child(1){
		margin-left:10px;
	}
	.order_information_item>view:nth-child(2){
		margin-right:10px;
		max-width: 60%;
		@include ellipsis(1);
	}

	.remark{
		margin-top: 10px;
		background-color: #FFFFFF;
		border-radius: 3px;
		padding: 10px 10px;
		display: flex;
		justify-content: space-between;
		text{
			color: #363636;
			font-size: 16px;
			font-weight: bold;
		}
		input{
			min-width: 250px;
		}
	}

	.foot-section{
		width: calc(100vw - 24px);
		padding: 12px;
		position:fixed;
		z-index:101;
		bottom: 0;
		left: 0;
		background-color: #FFFFFF;
	}
	.foot{
		background:#222222;
		height:45px;
		width: calc(100vw - 24px);
		border-radius: 20px;
		overflow: hidden;
		display:flex;
		align-items:center;
		justify-content:space-between;
		color: #ffffff;
		.footer_left{
		  /*margin-left:10px;*/
		}
		.footer_left>checkbox{
		  margin: 0 14px;
		  width: 22px;
		  height: 22px;
		}
		.footer_right{
		  display:flex;
		  align-items:center
		}
		.footer_right_price{
		  display: flex;
		  align-items: center;
		  color:#F66C0B;
		  font-size: 18px;
		  font-weight: bold;
		  margin-right:10px;
		}
		.footer_right_pay{
		  background:#09C15F;
		  text-align:center;
		  color:#fff;
		  height: 45px;
		  line-height:45px;
		  width:100px;
		}
	}
	button {
		border-radius: 0;
	}

</style>
